Ugly number¶
Time: O(LogN)=O(1); Space: O(1); easy
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example 1:
Input: num = 6
Output: True
Explanation:
6 = 2 x 3
Example 2:
Input: num = 8
Output: True
Explanation:
8 = 2 x 2 x 2
Example 3:
Input: num = 14
Output: False
Explanation:
14 includes another prime factor 7.
Notes:
1 is typically treated as an ugly number.
Input is within the 32-bit signed integer range: (-2^31, 2^31 - 1).
[1]:
class Solution1(object):
def isUgly(self, num) -> bool:
"""
:type num: int
:rtype: bool
"""
if num == 0:
return False
for i in [2, 3, 5]:
while num % i == 0:
num //= i
return num == 1
[2]:
s = Solution1()
num = 6
assert s.isUgly(num) == True
num = 8
assert s.isUgly(num) == True
num = 14
assert s.isUgly(num) == False